﻿using System;
using System.ComponentModel;
using System.Windows.Input;
using RG.Common.WPF.Commands;
using Microsoft.Practices.Unity;
using RG.Common;

namespace RG.Common.WPF.Dialogs
{
    [SupportDataBinding]
    public class EditableObjectDlgVM: IChildView, IWorkplaceObject
    {
        public IUnityContainer Cfg { get; set; }

        [Dependency]
        public IWorkplace Workplace { get; set; }

        public ICommand OkCmd { get; set; }
        public ICommand CancelCmd { get; set; }

        public string OkText { get; set; }
        public string CancelText { get; set; }

        [InjectionConstructor]
        public EditableObjectDlgVM(IUnityContainer cfg)
        {
            Cfg = cfg;
            OkCmd = new DelegateCommand(OnOk, CanOk);
            CancelCmd = new DelegateCommand(OnCancel, CanCancel);
            OkText = "Ok";
            CancelText = "Отмена";
        }

        private void OnOk()
        {
            if (CanOk())
                Workplace.CloseDialog(true);
        }

        private void OnCancel()
        {
            if (CanCancel())
                Workplace.CloseDialog(false);
        }

        public object ChildView { get; private set; }
        public object Child { get; private set; }

        public IEditableObject ChildEditableObject { get { return (IEditableObject)Child; } }

        public void SetChild<TPresenter>(TPresenter child)
        {
            Child = child;

            var view = Cfg.Resolve<IView<TPresenter>>();
            view.Presenter = child;
            ChildView = view;
        }

        public bool CanOk()
        {
            if (ChildEditableObject is IEditableDialogDataErrorInfo && ((IEditableDialogDataErrorInfo)ChildEditableObject).LastError() != String.Empty) return false; 

            ChildEditableObject.EndEdit();
            //if (Child is IWorkplaceObject)
            //{
            //    var wo = Child as IWorkplaceObject;
            //    return (wo == null) || wo.CanClose;
            //}
            return true;
        }

        public bool CanCancel()
        {
            ChildEditableObject.CancelEdit();
            return true;
        }

        public bool CanClose
        {
            get
            {
                var wo = Child as IWorkplaceObject;
                return (wo == null) || wo.CanClose;
            }
        }
    }
}